/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

 //自己写的递归
class Solution {
public:
    void reverse(TreeNode* root)
    {
        if(!root) return;
        reverse(root->left);
        reverse(root->right);
        TreeNode* tmp=nullptr;
        tmp=root->left;
        root->left=root->right;
        root->right=tmp;
    }
    TreeNode* invertTree(TreeNode* root) {
        if(!root) return nullptr;
        reverse(root);
        return root;     
    }
};

// 改进递归
// class Solution {
// public:
//     TreeNode* invertTree(TreeNode* root) {
//         if (!root)
//             return nullptr;
//         TreeNode* lNode = invertTree(root->left);
//         TreeNode* rNode = invertTree(root->right);
//         TreeNode* tmp = nullptr;
//         tmp = root->left;
//         root->left = root->right;
//         root->right = tmp;
//         return root;
//     }
// };

//使用栈
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(!root) return nullptr;
        stack<TreeNode*> S;
        S.push(root);
        while(!S.empty())
        {
            TreeNode* rt=S.top();

            TreeNode* tmp=nullptr;
            tmp=rt->left;
            rt->left=rt->right;
            rt->right=tmp;
            S.pop();
            if(rt->left) S.push(rt->left);
            if(rt->right) S.push(rt->right);
        }
        return root;
    }
};
